package com.keycloak.admin.services;


import com.keycloak.admin.model.base.VCodeModel;
import com.keycloak.admin.model.params.AliSmsParams;
import com.keycloak.admin.model.params.ReturnParams;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Service
public class VCodeService {
    /**
     * 用以缓存验证码的集合
     */
    private Map<String, VCodeModel> vCodeMap = new HashMap<>();

    /**
     * 向手机发送验证码
     *
     * @param cell
     * @return
     */
    public ReturnParams sendVCode(String cell,Integer business) {
        String vcode = null;
        try {
            vcode = SmsService.getVCode();//获取验证码
            AliSmsParams aliSmsParams = SmsService.sendVerificationCode(cell, business, vcode);
            if(aliSmsParams != null){

            if("OK".equalsIgnoreCase(aliSmsParams.getCode())){
                vCodeMap.put(cell, new VCodeModel(vcode, System.currentTimeMillis()));
                return new ReturnParams(0, "success", "验证码已经发送至您的手机！"+ vcode);
            }else{
                vCodeMap.put(cell, new VCodeModel(vcode, System.currentTimeMillis()));
                return new ReturnParams(1, "验证码发送失败！"+aliSmsParams.getMessage()+vcode,null);
            }

            }else{
                return new ReturnParams(1, "验证码发送失败！系统异常！",null);
            }

        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnParams(1, "验证码发送失败！", null);
        }
    }

    /**
     * 移除跟手机关联的验证码
     *
     * @param cell
     * @return
     */
    public boolean removeVCode(String cell) {
        vCodeMap.remove(cell);//移除这一条验证码
        return false;
    }

    public Map<String, VCodeModel> getvCodeMap() {
        return vCodeMap;
    }
}
